<template>
  <div>
    <SupInput :InpList="inpList" :BtnList="btnList" @clickFn="btnFn"></SupInput>
    <Suptable
      :isTag="true"
      :headerData="headerData"
      :tableData="tableData"
      :isPage="true"
      :border="true"
      :total="total"
      @handleSizeChange="handleSizeChange"
      @handleCurrentChange="handleCurrentChange"
      :current-page="pagenum"
      :pagesizeList="fenye"
      :pagesize="pagesize"
    >
      <template v-slot:tagSlot="{ row }">
        <div>
          <el-switch
            v-model="row.row.status"
            active-text="可用"
            @change="changState(row.row.status, row.row.id)"
            inactive-text="禁用"
          >
          </el-switch>
        </div>
      </template>
      <template v-slot:opera="{ row }">
        <div>
          <el-button type="primary" @click="goEdit(row.row)" size="small"
            >编辑</el-button
          >
          <el-button type="danger" @click="godelete(row.row.id)" size="small"
            >删除</el-button
          >
        </div>
      </template>
    </Suptable>
    <div>
      <el-dialog
        :title="isEdit ? '编辑' : '新增'"
        :visible.sync="dialogVisible"
        width="30%"
      >
        <div>
          <el-form
            :model="ruleForm"
            :rules="rules"
            ref="ruleForm"
            label-width="100px"
            class="demo-ruleForm"
          >
            <el-form-item label="生日" prop="birth" v-if="!isEdit">
              <el-date-picker
                v-model="ruleForm.birth"
                type="date"
                placeholder="选择日期"
                :value-format="`yyyy-MM-dd`"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="性别" prop="sex" v-if="!isEdit">
              <el-select v-model="ruleForm.sex" placeholder="请选择性别">
                <el-option label="男" value="0"></el-option>
                <el-option label="女" value="1"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="用户名" prop="name" v-if="!isEdit">
              <el-input v-model="ruleForm.name"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="ruleForm.email"></el-input>
            </el-form-item>
            <el-form-item label="手机号码" prop="phone">
              <el-input v-model="ruleForm.phone"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitForm('ruleForm')"
                >确定</el-button
              >
            </el-form-item>
          </el-form>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import {
  UserList,
  detUser,
  addUser,
  editUser,
  queryUser,
  alterUser,
} from "@/api/UserMock.js";
import Suptable from "@/components/Suptable";
import SupInput from "@/components/SupInput";
export default {
  name: "userDataList",
  data() {
    let validatormail = (rule, value, callback) => {
      let myreg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
      if (!myreg.test(value.trim()) || value.trim() == "") {
        callback(new Error("请输入正确邮箱"));
      } else {
        callback();
      }
    };
    let validatorphone = (rlue, value, callback) => {
      let myreg =
        /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/;
      if (!myreg.test(value.trim()) || value.trim() == "") {
        callback(new Error("请输入正确手机号"));
      } else {
        callback();
      }
    };
    return {
      pagenum: 1,
      pagesize: 10,
      total: 0,
      fenye: [5, 10, 15, 20],
      dialogVisible: false,
      isEdit: false,
      tableData: [],
      editId: "",
      headerData: [
        {
          prop: "id",
          label: "用户ID",
          width: "100",
        },
        {
          prop: "username",
          label: "用户名",
          width: "100",
        },
        {
          prop: "phone",
          label: "手机号码",
          width: "150",
        },
        {
          prop: "gender",
          label: "性别",
          width: "100",
        },
        {
          prop: "email",
          label: "邮箱",
          width: "200",
        },
        // {
        //   prop: "status",
        //   label: "状态",
        // },
        {
          prop: "userLevel",
          label: "用户等级",
        },
        {
          prop: "birth",
          label: "生日",
          width: "150",
        },
      ],
      ruleForm: {
        name: "",
        sex: "",
        phone: "",
        email: "",
        birth: "",
      },
      rules: {
        name: [{ required: true, message: "请输入用户名", trigger: "blur" }],
        sex: [{ required: true, message: "请选择性别", trigger: "change" }],
        birth: [{ required: true, message: "请选择生日", trigger: "change" }],
        email: [{ required: true, trigger: "blur", validator: validatormail }],
        phone: [{ required: true, trigger: "blur", validator: validatorphone }],
      },
      inpList: [
        {
          text: "请输入用户名",
          model: "",
        },
        {
          text: "请输入有手机号",
          model: "",
        },
      ],
      btnList: [
        {
          icon: "el-icon-search",
          name: "查找",
        },
        {
          icon: "el-icon-edit",
          name: "添加",
        },
      ],
    };
  },
  mounted() {
    let _self = this;
    _self.userList();
  },
  methods: {
    changState(status, id) {
      let _self = this;
      status = status ? 0 : 1;
      let data = { status, id };
      alterUser(data).then((res) => {
        // console.log(res);
        if (res.meta.status == 200) {
          _self.$message(res.meta.msg);
        }
      });
    },
    goEdit(row) {
      let _self = this;
      _self.isEdit = true;
      _self.dialogVisible = true;
      _self.ruleForm.email = row.email;
      _self.ruleForm.phone = row.phone;
      _self.editId = row.id;
      //  _self.ruleForm.name = "1";
      // _self.ruleForm.pass = "2";
      // _self.dialogVisible = true;
      // _self.dialogtype = type
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      let _self = this;
      _self.pagesize = val;
      _self.userList();
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      let _self = this;
      _self.pagenum = val;
      _self.userList();
    },
    godelete(id) {
      let _self = this;
      _self
        .$confirm("确定删除吗", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
        .then(() => {
          let data = { id };
          detUser(data).then((res) => {
            // console.log(res);
            if (res.meta.status == 200) {
              _self.$message({
                type: "success",
                message: "删除成功",
              });
              _self.userList();
            } else {
              _self.$message({
                type: "info",
                message: "res.meta.msg",
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    submitForm(formName) {
      let _self = this;
      _self.$refs[formName].validate((valid) => {
        if (valid) {
          if (!_self.isEdit) {
            let { name, sex, email, phone, birth } = _self.ruleForm;
            let data = {
              username: name,
              gender: sex,
              email,
              phone,
              birth,
            };
            addUser(data).then((res) => {
              // console.log(res);
              if (res.meta.status == "200") {
                _self.dialogVisible = false;
                _self.$refs[formName].resetFields();
                _self.userList();
              } else {
                _self.$message(res.meta.msg);
              }
            });
          } else {
            let data = {
              id: _self.editId,
              email: _self.ruleForm.email,
              phone: _self.ruleForm.phone,
            };
            editUser(data).then((res) => {
              // console.log(res);
              if (res.meta.status == 200) {
                _self.userList();
                _self.$message("更改成功");
                _self.dialogVisible = false;
                _self.$refs[formName].resetFields();
              }
            });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    userList() {
      let _self = this;
      let data = {
        pagenum: _self.pagenum,
        pagesize: _self.pagesize,
      };
      UserList(data).then((res) => {
        let _self = this;
        _self.tableData = [];
        for (let item of res.data.user) {
          let userData = {
            id: item.id,
            username: item.username,
            phone: item.phone,
            gender: item.gender == 0 ? "男" : "女",
            userLevel: item.userLevel == 1 ? "普通用户" : "代理",
            birth: item.birth,
            status: item.status == 0 ? true : false,
            email: item.email,
          };
          _self.tableData.push(userData);
        }
        _self.total = res.data.total;
        _self.pagenum = res.data.pagenum;
      });
    },
    btnFn(index) {//index==0 第一个按钮事假  index==1 第二个按钮事件
      let _self = this;
      if (index == 0) {
        let data = {
          username: _self.inpList[0].model,
          phone: _self.inpList[1].model,
        };
        queryUser(data).then((res) => {
          // console.log(res);
          _self.tableData = [];
          if (res.meta.status == 200) {
            for (let item of res.data.arr) {
              let userData = {
                id: item.id,
                username: item.username,
                phone: item.phone,
                gender: item.gender == 0 ? "男" : "女",
                userLevel: item.userLevel == 1 ? "普通用户" : "代理",
                birth: item.birth,
                status: item.status == 0 ? true : false,
                email: item.email,
              };
              _self.tableData.push(userData);
              _self.pagesize = res.data.pagesize;
              _self.total = res.data.total;
            }
            // _self.tableData = res.data.arr;
          } else {
            _self.pagesize = 10;
            _self.userList();
          }
        });
      } else if (index == 1) {
        let _self = this;
        _self.isEdit = false;
        _self.dialogVisible = true;
        _self.ruleForm = {
          name: "",
          sex: "",
          phone: "",
          email: "",
          birth: "",
        };
      }
    },
  },
  components: { Suptable, SupInput },
};
</script>